//base
import Taro, { Component } from '@tarojs/taro'
import { View, Text, ScrollView } from '@tarojs/components'
import { AtActivityIndicator } from 'taro-ui'
//redux
import { connect } from '@tarojs/redux'
import { DOREQUESTSEARCHPAGE } from './store/actions/pagesearchpage'
import { UPDATEPAGESEARCHPAGE } from './store/types/pagesearchpage'
//less
import './index.less'
//libs
import { showToast } from '../../../crossplatform/apiservice/toast'
import pagesearchpage from './store/reducers/pagesearchpage'
import { getStore } from '../../../store/index'
import { injectReducer } from '../../../store/reducerUtils'
import { getListRequest } from '../../../service/post-controller'
import { queryArchiveRequest } from '../../../service/user-archive-controller'
import { formatDataJobView } from '../../../service/format/job-view'
import tool from '../../../util/tool'
import { navigateTo, navigateBack } from '../../../crossplatform/apiservice/navigate'
import pagejumplist from '../../../configuration/pagejumplist.json'
import JobListItem from '../../../components/page-components/job-list-item'
import If from '../../../components/page-components/if'
import ShowEmpty from '../../../components/page-components/show-empty'
import { setStorageSync, getStorageSync } from '../../../crossplatform/apiservice/storage'
import AlumniListItem from '../../../components/page-components/alumni-list-item'
import { getGlobalData } from '../../../configuration/globaldata'

const store = getStore()
injectReducer(store, {
  key: 'pagesearchpage',
  reducer: pagesearchpage
})

const mapActiontoProps = dispatch => ({
  updateState(payload) {
    dispatch({
      type: UPDATEPAGESEARCHPAGE,
      payload: {
        ...payload
      }
    })
  },
  dorequest() {
    return new Promise(resolve => {
      let promise = DOREQUESTSEARCHPAGE()
      dispatch(promise)
      promise.payload.then(data => {
        resolve(data)
      })
    })
  }
})

@connect(
  ({ pagesearchpage, userinfo, landmark }) => ({
    ...pagesearchpage,
    role: userinfo.role,
    userId: userinfo.userId,
    landmarkName: landmark.landmarkName
  }),
  mapActiontoProps
)
class SearchPage extends Component {
  config = {
    navigationBarTitleText: '搜索'
  }

  constructor(props) {
    super(props)
    this.state = {
      value: '',
      showHistory: true,
      dataSource: [],
      page: 0,
      pageSize: 10,
      searchData: {},
      lastLandmarkName: '',
      dataOver: false,
      searchLoading: false
    }
  }

  componentWillMount() {
    //onLoad
    const { landmarkName } = this.props
    this.setState({
      lastLandmarkName: landmarkName
    })
  }

  componentDidMount() {
    //onready
  }

  componentDidShow() {
    //onshow
    this.queryWrap()
  }

  componentDidHide() {
    //onhide
  }

  componentWillUnmount() {
    //onUnload
    this.initData()
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.landmarkName && this.state.lastLandmarkName != nextProps.landmarkName) {
      this.setState({
        lastLandmarkName: nextProps.landmarkName
      })
      this.initData()
    }
  }

  initData = () => {
    // 初始化数据
    this.setState({
      page: 0,
      value: '',
      showHistory: true,
      dataSource: [],
      dataOver: false,
      searchLoading: false
    })
  }

  queryWrap = () => {
    // 初始化操作
    const { role } = this.props
    let searchDataStorage = getStorageSync('searchData')
    if (!searchDataStorage) {
      searchDataStorage = {
        c: [],
        b: []
      }
      setStorageSync('searchData', { ...searchDataStorage })
    }
    this.setState({
      searchData: role === 'personal' ? searchDataStorage.c : searchDataStorage.b
    })
  }

  goCity = tool.throttle(() => {
    // 跳转城市选择
    navigateTo({
      url: pagejumplist['city-location'].path
    })
  })

  goBack = () => {
    navigateBack()
  }

  onChange = e => {
    const { value } = e.detail
    this.setState({
      value
    })
    if (!value) {
      this.setState({
        showHistory: true
      })
    }
  }

  inputConfirm = tool.throttle(e => {
    // 搜索
    const { value } = e.detail
    this.setState(
      {
        page: 0,
        dataSource: [],
        dataOver: false
      },
      () => {
        this.searchRequest(value).then(() => {
          this.setSearchHistory(value)
        })
      }
    )
  })

  searchRequest = value => {
    return new Promise(resolve => {
      const { role } = this.props
      const { pageSize, page, searchLoading, dataSource, dataOver } = this.state
      let submitData = {}
      if (!dataOver && !searchLoading) {
        this.setState({
          searchLoading: true
        })
        if (role === 'personal') {
          submitData.name = value
          getListRequest({ pageSize, page: page + 1, postSearchCondition: submitData }).then(
            ({ data: { entry, code, message } }) => {
              let list = []
              if (code === 200) {
                if (entry.length < pageSize) {
                  this.setState({
                    dataOver: true
                  })
                }
                list = formatDataJobView(entry)
              } else {
                showToast({ title: message || '查询失败' })
              }
              resolve()
              this.setState({
                dataSource: [...dataSource, ...list],
                showHistory: false,
                page: page + 1,
                searchLoading: false
              })
            }
          )
        } else {
          submitData.query = value
          submitData.page = page + 1
          submitData.pageSize = pageSize
          queryArchiveRequest({ ...submitData }).then(({ data }) => {
            const { code, entry, message } = data
            let list = []
            if (code === 200) {
              if (entry.length < pageSize) {
                this.setState({
                  dataOver: true
                })
              }
              const globaldata = getGlobalData().education
              entry.map(item => {
                // 学历
                const educationId =
                  item.education >= 10 ? Math.floor(item.education / 10) : item.education
                let eduPre =
                  educationId && globaldata[educationId - 1] && globaldata[educationId - 1].name

                let workCategory = []
                let workNature = []
                let workPlace = []
                item &&
                  item.objective.map(comItem => {
                    let comItemParse = JSON.parse(comItem)
                    workCategory.push(comItemParse.workCategory[0])
                    workNature.push(comItemParse.workNature[0])
                    workPlace.push(comItemParse.workPlace[0])
                    return comItemParse
                  })

                item.education = !educationId ? '无教育信息' : eduPre

                item.workCategory = workCategory
                item.workNature = workNature
                item.workPlace = workPlace
                item.gender = item.gender
                item.id = item.userId
                item.userAvator = item.avatarUrl

                return item
              })
            } else {
              showToast({ title: message || '查询失败' })
            }
            resolve()
            this.setState({
              dataSource: [...dataSource, ...entry],
              showHistory: false,
              page: page + 1,
              searchLoading: false
            })
          })
        }
      }
    })
  }

  setSearchHistory = value => {
    // 存储搜索历史到缓存
    const searchDataStorage = getStorageSync('searchData')
    const { role } = this.props
    if (role === 'personal') {
      let c = [...searchDataStorage.c]
      c.push(value)
      c = this.unique4(c)
      setStorageSync('searchData', { ...searchDataStorage, c })
      this.setState({
        searchData: c
      })
    } else {
      let b = [...searchDataStorage.b]
      b.push(value)
      b = this.unique4(b)
      setStorageSync('searchData', { ...searchDataStorage, b })
      this.setState({
        searchData: b
      })
    }
  }

  clearHistory = tool.throttle(() => {
    // 清空搜索记录
    const { role } = this.props
    const searchDataStorage = getStorageSync('searchData')
    if (role === 'personal') {
      setStorageSync('searchData', { ...searchDataStorage, c: [] })
      this.setState({
        searchData: []
      })
    } else {
      setStorageSync('searchData', { ...searchDataStorage, b: [] })
      this.setState({
        searchData: []
      })
    }
  })

  onClickHistory = tool.throttle(e => {
    // 点击搜索历史
    const { name } = e.currentTarget.dataset
    this.setState(
      {
        page: 0,
        dataSource: [],
        value: name,
        dataOver: false
      },
      () => {
        this.searchRequest(name)
      }
    )
  })

  unique4 = arr => {
    // 数组去重
    var hash = []
    for (var i = 0; i < arr.length; i++) {
      for (var j = i + 1; j < arr.length; j++) {
        if (arr[i] === arr[j]) {
          ++i
        }
      }
      hash.push(arr[i])
    }
    return hash
  }

  bindClick = tool.throttle(data => {
    // 点击岗位
    const { id, companyId } = data
    navigateTo({
      url: `${pagejumplist['job-detail'].path}?id=${id}&companyId=${companyId}`
    })
  })

  goPersonalInfo = tool.throttle(index => {
    const { dataSource = [] } = this.state
    const dataSingle = dataSource[index]
    navigateTo({
      url: `${pagejumplist['person-detail'].path}?userId=${dataSingle.id}`
    })
  })

  getSearchData = () => {
    // scrollview 向下滚动获取页面
    const { value } = this.state
    this.searchRequest(value)
  }

  render() {
    const { value, showHistory, dataSource, searchData, dataOver, searchLoading } = this.state
    const { landmarkName, role } = this.props
    return (
      <View className="SearchPage_id16408">
        {searchLoading && <AtActivityIndicator mode="center" />}
        <View className="top-search">
          <View className="search-left">
            <View className="search-city" onClick={this.goCity}>
              <Text>{landmarkName || '上海'}</Text>
              <Image
                className="arrow"
                src="https://imagesize.hrwork.com/sp/files/f1b641a7-7e77-4489-9a7c-a35ce360e026.png"
              />
            </View>
            <View className="search-line" />
            <Input
              className="search-input"
              value={value}
              onInput={this.onChange}
              onConfirm={this.inputConfirm}
              placeholder={role === 'personal' ? "请输入职位或公司" : '请输入岗位类型或工作区域'}
              confirmType="search"
              focus
            />
          </View>
          <View className="search-right" onClick={this.goBack}>
            取消
          </View>
        </View>
        {showHistory && (
          <View className="search-history">
            <View className="history-title">
              <View className="history-right">搜索历史</View>
              <Image
                className="history-left"
                onClick={this.clearHistory}
                src="https://imagesize.hrwork.com/sp/files/6995ef1a-fc92-4dd3-bf15-07485553ff04.png"
              />
            </View>
            <View className="search-history-list">
              {searchData.map(item => {
                return (
                  <View
                    className="history-list-item"
                    data-name={item}
                    onClick={this.onClickHistory}
                  >
                    {item}
                  </View>
                )
              })}
            </View>
          </View>
        )}
        {!showHistory && (
          <If visible={dataSource.length > 0} renderElse={<ShowEmpty />}>
            <ScrollView className="search-list" scrollY onScrollToLower={this.getSearchData}>
              {dataSource.map((data, index) => {
                return role === 'personal' ? (
                  <JobListItem data={data} landmarkName={landmarkName} bindClick={this.bindClick} />
                ) : (
                  <AlumniListItem data={data} onTap={this.goPersonalInfo.bind(this, index)} />
                )
              })}
              {dataOver && <View className="data-over">已全部加载完毕</View>}
              {!dataOver && <View className="data-over">正在加载...</View>}
            </ScrollView>
          </If>
        )}
      </View>
    )
  }
}

export default SearchPage
